package com.smedi.ismedi.authority.starter.common;

import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;
import org.joda.time.DateTime;

import java.io.Serializable;
import java.sql.Timestamp;
import java.util.List;

/**
 * 底层服务端对于返回的数据不做rest处理
 */
@Data
@Accessors(chain = true)
public class ResponseData<T> implements Serializable {
    @ApiModelProperty(value = "服务名称")
    private String application;

    @ApiModelProperty(value = "请求是否成功")
    private boolean success;

    @ApiModelProperty(value = "请求编码")
    private String code = String.format("%05d", 0); // 默认成功

    @ApiModelProperty(value = "返回实体数据")
    private T data;

    @ApiModelProperty(value = "错误消息")
    private Object errorMsg;

    @ApiModelProperty(value = "具体错误信息")
    private Object exception;

    @ApiModelProperty(value = "服务器当前时间")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", locale = "zh", timezone = "GMT+8")
    private Timestamp currentTime;

    // 不带具体 Exception 失败
    public ResponseData<T> failure(String application, String code, String errorMsg) {
        this.application = application;
        this.success = false;
        this.code = code;
        this.errorMsg = errorMsg;
        this.setCurrentTime(new Timestamp(new DateTime().getMillis()));
        return this;
    }

    // 带有 Exception 失败
    public ResponseData<T> failure(String application, String code, String errorMsg, Object e) {
        this.application = application;
        this.success = false;
        this.code = code;
        this.errorMsg = errorMsg;
        this.setCurrentTime(new Timestamp(new DateTime().getMillis()));
        this.exception = e;
        return this;
    }

    // 实体对象
    public <T> ResponseData<T> success(T data) {
        ResponseData<T> response = new ResponseData<T>();
        response.setSuccess(true);
        response.setCurrentTime(new Timestamp(new DateTime().getMillis()));
        response.setData(data);
        return response;
    }

    // 数组对象
    public <T> ResponseData<List<T>> success(List<T> list) {
        ResponseData<List<T>> response = new ResponseData<List<T>>();
        response.setSuccess(true);
        response.setCurrentTime(new Timestamp(new DateTime().getMillis()));
        response.setData(list);
        return response;
    }
}
